import { http } from "@/utils/http";
import axios from "axios";
// import { getToken } from "@/utils/auth";
import { getToken175, getToken43 } from "@/utils/token";

type Result = {
  message: string;
  data: any;
  code: number;
};

// 为task API添加Authorization头的辅助函数
const taskRequest = <T>(method: string, url: string, data?: object) => {
  const token = getToken175(); // 每次调用都获取最新的token
  return http.request<T>(method as any, url, {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

const remoteRequest = <T>(method: string, url: string, data?: object) => {
  const remoteToken = getToken43(); // 每次调用都获取最新的token
  return http.request<T>(method as any, url, {
    data,
    headers: {
      Authorization: remoteToken ? `Bearer ${remoteToken}` : undefined,
    },
  });
};

/** 获取资产列表 */
export const getAssetList = ({
  data,
  type = "asset",
}: {
  data: object;
  type: string;
}) => {
  return taskRequest<Result>("post", `/api/api/${type}/data`, data);
};

/** 风险概览仪表板数据接口 */
export const getRiskOverview = (data?: {
  template_id?: number;
  day?: number;
}) => {
  return taskRequest<Result>("post", "/api/risk/statistics/overview", data);
};

/** 部门排名（含整体概览与风险分布），用于仪表盘 */
export const getDepartmentRanking = (data?: {
  template_id?: number;
  limit?: number;
}) => {
  return taskRequest<Result>("post", "/api/risk/department/ranking", data);
};

/** 多部门趋势（可选，用于趋势图） */
export const getDepartmentTrendAll = (data?: {
  template_id?: number;
  days?: number;
  top_n?: number;
}) => {
  return taskRequest<Result>("post", "/api/risk/department/trend/all", data);
};

/** 获取单个部门详情 */
export const getDepartmentDetail = (data?: {
  department_name: string;
  template_id?: number;
}) => {
  return taskRequest<Result>("post", "/api/risk/department/detail", data);
};

/** 对比多个部门 */
export const compareDepartments = (data?: {
  department_names: string[];
  template_id?: number;
}) => {
  return taskRequest<Result>("post", "/api/risk/department/compare", data);
};

/** 获取单部门趋势分析 */
export const getDepartmentTrend = (data?: {
  department_name: string;
  template_id?: number;
  days?: number;
}) => {
  return taskRequest<Result>("post", "/api/risk/department/trend", data);
};

/** 保存排名快照 */
export const saveDepartmentSnapshot = (data?: { template_id?: number }) => {
  return taskRequest<Result>(
    "post",
    "/api/risk/department/snapshot/save",
    data
  );
};

/** 查询部门资产列表 */
export const queryDepartmentAssets = (data?: {
  department_name: string;
  page?: number;
  page_size?: number;
  order_by?: string;
  order_direction?: "asc" | "desc";
  risk_level?: string;
  template_id?: number;
}) => {
  return taskRequest<Result>("post", "/api/risk/score/query", data);
};

/** 计算资产评分 */
export const calculateAssetScore = (data?: {
  asset_ip: string;
  template_id?: number;
  include_remediation?: boolean;
}) => {
  return taskRequest<Result>("post", "/api/risk/score/calculate", data);
};

/** 查询评分列表 */
export const getScoreList = (data?: {
  page?: number;
  page_size?: number;
  asset_ip?: string;
  risk_level?: string;
  score_min?: number;
  score_max?: number;
  template_id?: number;
}) => {
  return taskRequest<Result>("post", "/api/risk/score/list", data);
};

/** 获取资产评分详情 */
export const getAssetScoreDetail = (data?: {
  asset_ip: string;
  template_id?: number;
  include_raw_data?: boolean;
}) => {
  return taskRequest<Result>("post", "/api/risk/score/detail", data);
};

/** 查询评分历史 */
export const getScoreHistory = (data?: {
  asset_ip: string;
  days?: number;
  page?: number;
  page_size?: number;
  template_id?: number;
}) => {
  return taskRequest<Result>("post", "/api/risk/score/history", data);
};

/** 获取整改建议 */
export const getRemediationPlan = (data?: {
  asset_ip: string;
  template_id?: number;
}) => {
  return taskRequest<Result>("post", "/api/risk/remediation/plan", data);
};

/** 获取修复建议（新接口） */
export const getRemediationAdvice = (data?: {
  asset_ip: string;
  template_id?: number;
}) => {
  return taskRequest<Result>("post", "/api/risk/remediation/advice", data);
};

/** 标记误报 */
export const markFalsePositive = (data?: {
  asset_ip: string;
  dimension_code: string;
  false_positive_reason: string;
  evidence?: string;
  handling_method?: "exclude_from_score" | "adjust_score" | "mark_only";
  score_adjustment?: number;
  marked_by?: string;
}) => {
  return taskRequest<Result>("post", "/api/risk/false_positive/mark", data);
};

/** 取消误报标记 */
export const unmarkFalsePositive = (data?: {
  asset_ip: string;
  dimension_code: string;
  unmarked_by?: string;
  unmarked_reason?: string;
}) => {
  return taskRequest<Result>("post", "/api/risk/false_positive/unmark", data);
};

/** 导出评分数据 */
export const exportScoreData = (data?: {
  format?: "excel" | "csv";
  risk_level?: string;
  asset_ip?: string;
  template_id?: number;
  min_score?: number;
  max_score?: number;
  department?: string;
  order_by?: string;
  max_export?: number;
}) => {
  return taskRequest<Result>("post", "/api/risk/score/export", data);
};

/** 导出历史记录数据（返回Blob） */
export const exportHistoryData = async (data?: {
  format?: "excel" | "csv";
  filters?: {
    time_range?: {
      start_date?: string;
      end_date?: string;
    };
    asset_ip?: string;
    risk_levels?: string[];
    change_types?: string[];
    score_range?: {
      min?: number;
      max?: number;
    };
    department_name?: string;
    template_id?: number;
  };
  order_by?: "calculated_at" | "total_score" | "score_change";
  order_direction?: "asc" | "desc";
}) => {
  // 直接使用 axios 绕过响应拦截器，避免 Blob 被当作 JSON 处理
  const token = getToken175();

  // 转换参数格式，适配 /api/risk/score/export 接口
  const exportParams: any = {
    format: data?.format || "excel",
  };

  // 转换筛选条件
  if (data?.filters) {
    const filters = data.filters;
    if (filters.asset_ip) exportParams.asset_ip = filters.asset_ip;
    if (filters.risk_levels && filters.risk_levels.length > 0) {
      exportParams.risk_level = filters.risk_levels[0]; // 接口可能只支持单个风险等级
    }
    if (filters.score_range) {
      exportParams.min_score = filters.score_range.min;
      exportParams.max_score = filters.score_range.max;
    }
    if (filters.department_name)
      exportParams.department = filters.department_name;
    if (filters.template_id) exportParams.template_id = filters.template_id;
  }

  if (data?.order_by) exportParams.order_by = data.order_by;
  if (data?.order_direction)
    exportParams.order_direction = data.order_direction;

  const response = await axios.post("/api/risk/score/export", exportParams, {
    headers: {
      "Content-Type": "application/json",
      Authorization: token ? `Bearer ${token}` : undefined,
    },
    responseType: "blob",
  });

  return response.data; // 返回 Blob 对象
};

/** 误报列表 */
export const getFalsePositiveList = (data?: {
  page?: number;
  page_size?: number;
  asset_ip?: string;
  dimension_code?: string;
  marked_by?: string;
  start_date?: string;
  end_date?: string;
}) => {
  return taskRequest<Result>("post", "/api/risk/false-positive/list", data);
};

/** 误报记录列表查询（增强版） */
export const getFalsePositiveListEnhanced = (data?: {
  page?: number;
  page_size?: number;
  asset_ip?: string;
  dimension_code?: string;
  status?: "active" | "inactive" | "all";
  review_status?: "reviewed" | "pending";
  marked_by?: string;
  reviewed_by?: string;
  start_time?: string;
  end_time?: string;
  keyword?: string;
  sort_field?:
    | "marked_at"
    | "reviewed_at"
    | "asset_ip"
    | "dimension_code"
    | "id";
  sort_order?: "asc" | "desc";
}) => {
  return taskRequest<Result>(
    "post",
    "/api/risk/false-positive/list_enhanced",
    data
  );
};

/** 误报统计数据查询 */
export const getFalsePositiveStatistics = () => {
  return taskRequest<Result>("get", "/api/risk/false-positive/statistics");
};

/** 误报详情查询 */
export const getFalsePositiveDetail = (data?: { id: number }) => {
  return taskRequest<Result>("post", "/api/risk/false-positive/detail", data);
};

/** 提交误报申请 */
export const submitFalsePositive = (data?: {
  asset_ip: string;
  dimension_code: string;
  false_positive_reason: string;
  evidence?: string;
  handling_method?: "exclude_from_score" | "adjust_score" | "mark_only";
  score_adjustment?: number;
  marked_by?: string;
}) => {
  return taskRequest<Result>("post", "/api/risk/false-positive/submit", data);
};

/** 确认误报 */
export const confirmFalsePositive = (data?: {
  id: number;
  reviewed_by?: string;
  review_note?: string;
}) => {
  return taskRequest<Result>("post", "/api/risk/false-positive/confirm", data);
};

/** 拒绝误报（确认非误报） */
export const rejectFalsePositive = (data?: {
  id: number;
  reviewed_by: string;
  reject_reason?: string;
}) => {
  return taskRequest<Result>("post", "/api/risk/false-positive/reject", data);
};

/** 忽略误报 */
export const ignoreFalsePositive = (data?: {
  id: number;
  ignored_by: string;
  ignore_reason?: string;
}) => {
  return taskRequest<Result>("post", "/api/risk/false-positive/ignore", data);
};

/** 查询白名单规则列表 */
export const getWhitelistRuleList = (data?: {
  page?: number;
  page_size?: number;
  rule_type?: "ip" | "ip_range" | "port" | "cve" | "dimension" | "custom";
  is_enabled?: boolean;
  keyword?: string;
  sort_by?: "created_at" | "updated_at" | "match_count";
  sort_order?: "asc" | "desc";
}) => {
  return taskRequest<Result>(
    "post",
    "/api/risk/false-positive/whitelist/list",
    data
  );
};

/** 创建白名单规则 */
export const createWhitelistRule = (data?: {
  rule_name: string;
  rule_type: "ip" | "ip_range" | "port" | "cve" | "dimension" | "custom";
  rule_description?: string;
  match_condition: {
    field: string;
    operator: "equals" | "contains" | "in_range" | "regex" | "in";
    value: string | number | string[];
  };
  applicable_dimensions?: string[];
  effective_start?: string;
  effective_end?: string;
  is_enabled?: boolean;
  created_by?: string;
}) => {
  return taskRequest<Result>(
    "post",
    "/api/risk/false-positive/whitelist/create",
    data
  );
};

/** 更新白名单规则 */
export const updateWhitelistRule = (data?: {
  id: number;
  rule_name?: string;
  rule_description?: string;
  match_condition?: {
    field: string;
    operator: "equals" | "contains" | "in_range" | "regex" | "in";
    value: string | number | string[];
  };
  applicable_dimensions?: string[];
  effective_start?: string;
  effective_end?: string;
  is_enabled?: boolean;
}) => {
  return taskRequest<Result>(
    "post",
    "/api/risk/false-positive/whitelist/update",
    data
  );
};

/** 删除白名单规则 */
export const deleteWhitelistRule = (data?: { id: number }) => {
  return taskRequest<Result>(
    "post",
    "/api/risk/false-positive/whitelist/delete",
    data
  );
};

/** 撤销误报 */
export const revokeFalsePositive = (data?: { id: number }) => {
  return taskRequest<Result>("post", "/api/risk/false-positive/revoke", data);
};

/** 更新误报 */
export const updateFalsePositive = (data?: {
  id: number;
  false_positive_reason?: string;
  evidence?: string;
  handling_method?: "exclude_from_score" | "adjust_score" | "mark_only";
  adjustment_value?: number;
}) => {
  return taskRequest<Result>("post", "/api/risk/false-positive/update", data);
};

/** 批量评分 */
export const batchCalculateScore = (data?: {
  asset_ips: string[];
  template_id?: number;
  send_notification?: boolean;
  generate_report?: boolean;
}) => {
  return taskRequest<Result>("post", "/api/risk/score/batch/calculate", data);
};

/** 一键评分所有资产（异步） */
export const batchScoreAllCompliance = (data?: { template_id?: number }) => {
  return taskRequest<Result>(
    "post",
    "/api/risk/score/batch_all_compliance",
    data
  );
};

/** 查询评分任务状态 */
export const getScoreTaskStatus = (taskId: string) => {
  const token = getToken175();
  return http.request<Result>("get", `/api/risk/score/task/status`, {
    params: {
      task_id: taskId,
    },
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

/** 获取评分模板列表 */
export const getScoreTemplateList = () => {
  return taskRequest<Result>("get", "/api/risk/template/list");
};

/** 创建模板 */
export const createTemplate = (data?: {
  template_name: string;
  template_code: string;
  version?: string;
  description?: string;
  total_score?: number;
  risk_level_thresholds?: {
    safe?: number;
    low?: number;
    medium?: number;
    high?: number;
    critical?: number;
  };
  is_active?: boolean;
  is_default?: boolean;
  created_by?: string;
  dimensions?: Array<{
    dimension_code: string;
    dimension_name: string;
    dimension_description?: string;
    max_score: number;
    weight?: number;
    data_source_type?: string;
    data_source_config?: any;
    calculation_type?: string;
    calculation_config?: any;
    aggregation_mode?: string;
    aggregation_config?: any;
    display_order?: number;
    is_enabled?: boolean;
  }>;
}) => {
  return taskRequest<Result>("post", "/api/risk/template/create", data);
};

/** 更新模板 */
export const updateTemplate = (data?: {
  id: number;
  template_name?: string;
  description?: string;
  total_score?: number;
  risk_level_thresholds?: {
    safe?: number;
    low?: number;
    medium?: number;
    high?: number;
    critical?: number;
  };
  is_active?: boolean;
  is_default?: boolean;
}) => {
  return taskRequest<Result>("post", "/api/risk/template/update", data);
};

/** 删除模板 */
export const deleteTemplate = (data?: { template_id: number }) => {
  return taskRequest<Result>("post", "/api/risk/template/delete", data);
};

/** 设置默认模板 */
export const setDefaultTemplate = (data?: { id: number }) => {
  return taskRequest<Result>("post", "/api/risk/template/set-default", data);
};

/** 激活/停用模板 */
export const toggleTemplateActive = (data?: {
  id: number;
  is_active: boolean;
}) => {
  return taskRequest<Result>("post", "/api/risk/template/toggle-active", data);
};

/** 查看模板使用情况 */
export const getTemplateUsage = (data?: { id: number }) => {
  return taskRequest<Result>("post", "/api/risk/template/usage", data);
};

/** 获取维度列表 */
export const getDimensionList = (data?: {
  page?: number;
  page_size?: number;
  dimension_name?: string;
  template_id?: number;
  is_enabled?: boolean;
  dimension_code?: string;
  sort_by?: "display_order" | "created_at" | "dimension_name" | "max_score";
  sort_order?: "asc" | "desc";
  filters?: {
    dimension_name?: string;
    dimension_code?: string;
    template_id?: number;
    is_enabled?: boolean;
  };
}) => {
  return taskRequest<Result>("post", "/api/risk/dimension/list", data);
};

/** 获取维度统计信息 */
export const getDimensionStatistics = () => {
  return taskRequest<Result>("get", "/api/risk/dimension/statistics");
};

/** 启用维度 */
export const enableDimension = (data?: {
  dimension_id?: number;
  dimension_ids?: number[];
}) => {
  return taskRequest<Result>("post", "/api/risk/dimension/enable", data);
};

/** 禁用维度 */
export const disableDimension = (data?: {
  dimension_id?: number;
  dimension_ids?: number[];
}) => {
  return taskRequest<Result>("post", "/api/risk/dimension/disable", data);
};

/** 批量更新维度顺序 */
export const batchUpdateOrder = (data?: {
  dimensions: Array<{ id: number; sort_order: number }>;
}) => {
  return taskRequest<Result>(
    "post",
    "/api/risk/dimension/batch_update_order",
    data
  );
};

/** 创建维度 */
export const createDimension = (data?: {
  template_id: number;
  dimension_code: string;
  dimension_name: string;
  dimension_description?: string;
  max_score: number;
  weight?: number;
  data_source_type?: string;
  data_source_config?: any;
  calculation_type?: string;
  calculation_config?: any;
  aggregation_mode?: string;
  aggregation_config?: any;
  display_order?: number;
  is_enabled?: boolean;
}) => {
  return taskRequest<Result>("post", "/api/risk/dimension/create", data);
};

/** 更新维度 */
export const updateDimension = (data?: {
  dimension_id: number;
  dimension_name?: string;
  dimension_description?: string;
  max_score?: number;
  weight?: number;
  data_source_type?: string;
  data_source_config?: any;
  calculation_type?: string;
  calculation_config?: any;
  aggregation_mode?: string;
  aggregation_config?: any;
  display_order?: number;
  is_enabled?: boolean;
}) => {
  return taskRequest<Result>("post", "/api/risk/dimension/update", data);
};

/** 删除维度 */
export const deleteDimension = (data?: { dimension_id: number }) => {
  return taskRequest<Result>("post", "/api/risk/dimension/delete", data);
};

/** 调整维度顺序 */
export const reorderDimensions = (data?: {
  template_id: number;
  dimension_orders: Array<{ id: number; display_order: number }>;
}) => {
  return taskRequest<Result>("post", "/api/risk/dimension/reorder", data);
};

/** 测试维度计算 */
export const testDimensionCalculation = (data?: {
  dimension_id: number;
  test_ip?: string;
}) => {
  return taskRequest<Result>("post", "/api/risk/dimension/test", data);
};

/** 获取维度详情 */
export const getDimensionDetail = (data?: { dimension_id: number }) => {
  return taskRequest<Result>("post", "/api/risk/dimension/detail", data);
};

/** 获取维度配置元数据 */
export const getDimensionConfigMetadata = () => {
  return taskRequest<Result>("get", "/api/risk/dimension/config_metadata");
};

/** 获取模板配置元数据 */
export const getTemplateConfigMetadata = () => {
  return taskRequest<Result>("get", "/api/risk/template/config_metadata");
};

/** 复制维度 */
export const copyDimension = (data?: {
  source_dimension_id: number;
  target_template_id: number;
  new_dimension_code?: string;
  new_dimension_name?: string;
}) => {
  return taskRequest<Result>("post", "/api/risk/dimension/copy", data);
};

/** 获取统计分析数据 */
export const getAnalyticsData = (data?: {
  template_id?: number;
  days?: number;
  start_date?: string;
  end_date?: string;
}) => {
  return taskRequest<Result>("post", "/api/risk/analytics/data", data);
};

/** 导出统计分析报告 */
export const exportAnalyticsReport = (data?: {
  template_id?: number;
  days?: number;
  format?: "excel" | "pdf";
}) => {
  return taskRequest<Result>("post", "/api/risk/analytics/export", data);
};

/** 获取评分历史列表 */
export const getHistoryList = (data?: {
  page?: number;
  page_size?: number;
  filters?: {
    time_range?: {
      start_date?: string;
      end_date?: string;
    };
    asset_ip?: string;
    risk_levels?: string[];
    change_types?: string[];
    score_range?: {
      min?: number;
      max?: number;
    };
    department_name?: string;
    template_id?: number;
  };
  order_by?: "calculated_at" | "total_score" | "score_change";
  order_direction?: "asc" | "desc";
}) => {
  return taskRequest<Result>("post", "/api/risk/score/history/list", data);
};

/** 获取历史统计数据 */
export const getHistoryStatistics = (data?: {
  filters?: {
    time_range?: {
      start_date?: string;
      end_date?: string;
    };
    asset_ip?: string;
    risk_levels?: string[];
    change_types?: string[];
    score_range?: {
      min?: number;
      max?: number;
    };
    department_name?: string;
    template_id?: number;
  };
}) => {
  return taskRequest<Result>(
    "post",
    "/api/risk/score/history/statistics",
    data
  );
};

/** 获取历史图表数据 */
export const getHistoryChartData = (data?: {
  filters?: {
    time_range?: {
      start_date?: string;
      end_date?: string;
    };
    asset_ip?: string;
    risk_levels?: string[];
    change_types?: string[];
    score_range?: {
      min?: number;
      max?: number;
    };
    department_name?: string;
    template_id?: number;
  };
}) => {
  return taskRequest<Result>("post", "/api/risk/score/history/chart", data);
};

/** 获取历史详情 */
export const getHistoryDetail = (data?: { history_id: number }) => {
  return taskRequest<Result>("post", "/api/risk/score/history/detail", data);
};

/** 获取历史对比数据 */
export const getHistoryCompare = (data?: {
  asset_ip: string;
  base_history_id: number;
  compare_history_id: number;
}) => {
  return taskRequest<Result>("post", "/api/risk/score/history/compare", data);
};

// ==================== 模板管理接口 ====================

/** 获取模板列表 */
export const getTemplateList = (data?: {
  page?: number;
  page_size?: number;
  filters?: {
    template_name?: string;
    template_code?: string;
    is_active?: boolean;
  };
  order_by?: "created_at" | "usage_count" | "template_name";
  order_direction?: "asc" | "desc";
}) => {
  return taskRequest<Result>("post", "/api/risk/template/list", data);
};

/** 获取模板统计数据 */
export const getTemplateStatistics = () => {
  return taskRequest<Result>("get", "/api/risk/template/statistics");
};

/** 获取模板详情 */
export const getTemplateDetail = (data?: { template_id: number }) => {
  return taskRequest<Result>("post", "/api/risk/template/detail", data);
};

/** 启用模板 */
export const enableTemplate = (data?: { template_id: number }) => {
  return taskRequest<Result>("post", "/api/risk/template/enable", data);
};

/** 禁用模板 */
export const disableTemplate = (data?: { template_id: number }) => {
  return taskRequest<Result>("post", "/api/risk/template/disable", data);
};

/** 复制模板 */
export const copyTemplate = (data?: {
  template_id: number;
  new_template_name?: string;
  new_template_code?: string;
  created_by?: string;
}) => {
  return taskRequest<Result>("post", "/api/risk/template/copy", data);
};

/** 验证模板配置 */
export const validateTemplate = (data?: { template_id: number }) => {
  return taskRequest<Result>("post", "/api/risk/template/validate", data);
};

/** 获取模板使用统计 */
export const getTemplateUsageStats = (data?: { template_id: number }) => {
  return taskRequest<Result>("post", "/api/risk/template/usage_stats", data);
};
